/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.ap.web;

import java.io.File;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.ap.entity.*;
import com.jeeplus.modules.ap.mapper.PaymentDetilMapper;
import com.jeeplus.modules.ap.service.ApplicationApprovalService;
import com.jeeplus.modules.ap.service.PaymentApplicationService;
import com.jeeplus.modules.ap.util.FksqPrint;
import com.jeeplus.modules.fee.entity.Payment;
import com.jeeplus.modules.fee.entity.PaymentDetail;
import com.jeeplus.modules.infor.entity.Department;
import com.jeeplus.modules.infor.entity.Staff;
import com.jeeplus.modules.infor.service.DepartmentService;
import com.jeeplus.modules.infor.service.ProjectService;
import com.jeeplus.modules.infor.service.StaffService;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.tms.util.FileUtil;
import com.jeeplus.modules.wms.util.CopyUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.ap.service.ProcurementApplicationService;

/**
 * 采购申请Controller
 * @author LCH
 * @version 2018-12-12
 */
@Controller
@RequestMapping(value = "${adminPath}/ap/procurementApplication")
public class ProcurementApplicationController extends BaseController {

	@Autowired
	private ProcurementApplicationService procurementApplicationService;
	@Autowired
	private StaffService staffService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private PaymentApplicationService service;
	@Autowired
	private PaymentApplicationService paymentApplicationService;
	@Autowired
	private PaymentDetilMapper paymentDetilMapper;
	@Autowired
	private ApplicationApprovalService applicationApprovalService;
	@ModelAttribute
	public ProcurementApplication get(@RequestParam(required=false) String id) {
		ProcurementApplication entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = procurementApplicationService.get(id);
		}
		if (entity == null){
			entity = new ProcurementApplication();
		}
		return entity;
	}
	
	/**
	 * 采购申请列表页面
	 */
	@RequiresPermissions("ap:procurementApplication:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/ap/procurementApplicationList";
	}
	/**
	 * 采购申请列表页面
	 */
	@RequiresPermissions("ap:procurementApplication:list")
	@RequestMapping(value = "list1")
	public String list1() {
		return "modules/ap/2/procurementApplicationList";
	}

	/**
	 * 调用打印页面
	 */
	@RequestMapping(value = "dayin")
	public String dayin(HttpServletRequest request,ProcurementApplication procurementApplication, Model model) throws Exception {

		//模版文件目录
		String templateFile = request.getSession().getServletContext().getRealPath("static/common/pdf/stenail/cgsq.pdf");

		//要合并的pdf所在文件夹
		String folder = request.getSession().getServletContext().getRealPath("static/common/pdf/example/");

		FksqPrint print=new FksqPrint();
		//用于存放需要合并的pdf文件名
		List<String> filelist = new ArrayList<String>();
		//时间戳命名要合并的pdf并加入list
		String filewei = "cgsq"+new Date().getTime() + ".pdf";
		//要合并的pdf目录
		String outFile = folder + "/"+filewei;
		File file = new File(outFile);
		if (!file.exists()) {
			try {
				file.createNewFile();
				System.out.println("创建成功!");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		ApplicationApproval a=new ApplicationApproval();
		a.setCgsq(procurementApplication.getId());
		List<ApplicationApproval> li=applicationApprovalService.findList(a);
		print.updatePdfa1(procurementApplication,li, templateFile, file);
		filelist.add(filewei);
		//}





		//合并后pdf所在文件夹
		String outPdfFileqian = request.getSession().getServletContext().getRealPath("static/common/pdf/print/");
		//合并后pdf文件目录
		String outPdfFile = outPdfFileqian+"/cgsq"+new Date().getTime() + ".pdf";
		//合并pdf方法
		print.mergePdf(folder, outPdfFile,filelist);
//定时删除合并前的文件以及合并后的文件
		Timer timer = new Timer();//实例化Timer类
		timer.schedule(new TimerTask() {
			public void run() {
				try {
					FileUtil.deleteFile(outPdfFile);
					for (int i = 0; i < filelist.size(); i++){
						FileUtil.deleteFile(folder + File.separator + filelist.get(i));
						System.out.println("删除文件成功");}

				} catch (Exception e) {

				} finally {
					this.cancel();
				}

			}
		}, 50000);//五万毫秒 50秒
		//将合并后的pdf目录传到jsp供读取
		request.setAttribute("outPdfFile",outPdfFile);
		return "modules/ap/print/pdf";
	}

	/**
	 * 采购申请列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:procurementApplication:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(ProcurementApplication procurementApplication, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.getUseroffice().equals("总部")){
			procurementApplication.setPro(UserUtils.getUseroffice());
		}
		Page<ProcurementApplication> page = procurementApplicationService.findPage(new Page<ProcurementApplication>(request, response), procurementApplication);
		return getBootstrapData(page);
	}
	/**
	 * 采购申请列表数据
	 */
	@ResponseBody
	@RequiresPermissions("ap:procurementApplication:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(ProcurementApplication procurementApplication, HttpServletRequest request, HttpServletResponse response, Model model) {
		if(!UserUtils.getUseroffice().equals("总部")){
			procurementApplication.setPro(UserUtils.getUseroffice());
		}
		procurementApplication.setStatus("总经理已审批");
		Page<ProcurementApplication> page = procurementApplicationService.findPage(new Page<ProcurementApplication>(request, response), procurementApplication);
		return getBootstrapData(page);
	}
	/**
	 * 查看，增加，编辑采购申请表单页面
	 */
	@RequiresPermissions(value={"ap:procurementApplication:view","ap:procurementApplication:add","ap:procurementApplication:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(ProcurementApplication procurementApplication, Model model) {
		if(procurementApplication.getIsNewRecord()){
			procurementApplication.setStatus("已创建");
			procurementApplication.setCgzt("未采购");
			procurementApplication.setZje("0");
			procurementApplication.setZjehs("0");
			procurementApplication.setPro(UserUtils.getUseroffice());
			Department d=new Department();
			d.setProject(projectService.findUniqueByProperty("name",UserUtils.getUseroffice()));
			d=departmentService.findList(d).get(0);
			d=departmentService.get(d.getId());
			procurementApplication.setBm(d.getName());
			procurementApplication.setDate(new Date());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			String code=UserUtils.getUserAre()+sdf.format(new Date());
			ProcurementApplication p=new ProcurementApplication();
			p.setCode(code);
			List<ProcurementApplication> list=procurementApplicationService.findList(p);
			if(list==null||list.size()<1){
				procurementApplication.setCode(code+"001"+"CGSQ");
			}else{
				if(list.size()/10==0){
					procurementApplication.setCode(code+"00"+(list.size()+1)+"CGSQ");
				}else
				if(list.size()/100==0){
					procurementApplication.setCode(code+"0"+(list.size()+1)+"CGSQ");
				}else{procurementApplication.setCode(code+(list.size()+1)+"CGSQ");}

			}
			Staff staff =new Staff();
			staff.setProjectName(UserUtils.getUseroffice());
			List<Staff> l=staffService.findList(staff);
			for(Staff s:l){
				if(staffService.get(s.getId()).getPosition().getName().contains("财务")){
					procurementApplication.setSqr(s.getName());
				}
			}
		}
		model.addAttribute("procurementApplication", procurementApplication);
		return "modules/ap/procurementApplicationForm";
	}
	/**
	 * 查看，增加，编辑采购申请表单页面
	 */
	@RequiresPermissions(value={"ap:procurementApplication:view","ap:procurementApplication:add","ap:procurementApplication:edit"},logical=Logical.OR)
	@RequestMapping(value = "form1")
	public String form1(ProcurementApplication procurementApplication, Model model) {
		model.addAttribute("procurementApplication", procurementApplication);
		return "modules/ap/1/procurementApplicationForm";
	}
	/**
	 * 保存采购申请
	 */
	@ResponseBody
	@RequiresPermissions(value={"ap:procurementApplication:add","ap:procurementApplication:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(ProcurementApplication procurementApplication, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		NumberFormat nf = NumberFormat.getInstance();
		if (!beanValidator(model, procurementApplication)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}

		List<ApplicationDetil> list=procurementApplication.getApplicationDetilList();
		int bhs=0;
		int hs=0;
		for(ApplicationDetil a:list){
			bhs+=Integer.parseInt(a.getZj());
			hs+=Integer.parseInt(a.getZjhs());
		}
		procurementApplication.setZje(bhs+"");
		procurementApplication.setZjehs(hs+"");
		//新增或编辑表单保存
		procurementApplicationService.save(procurementApplication);//保存
		j.setSuccess(true);
		j.setMsg("保存采购申请成功");
		return j;
	}
	/**
	 * 保存采购申请
	 */
	@ResponseBody
	@RequiresPermissions(value={"ap:procurementApplication:add","ap:procurementApplication:edit"},logical=Logical.OR)
	@RequestMapping(value = "save1")
	public AjaxJson save1(ProcurementApplication procurementApplication, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		NumberFormat nf = NumberFormat.getInstance();
		if (!beanValidator(model, procurementApplication)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		procurementApplication.setCgzt("已采购");
		procurementApplicationService.save(procurementApplication);//保存
		j.setSuccess(true);
		j.setMsg("保存采购申请成功");
		return j;
	}
	/**
	 * 确认提交
	 */
	@ResponseBody
	@RequestMapping(value = "qr")
	public AjaxJson qr(ProcurementApplication procurementApplication, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		procurementApplication.setStatus("已确认待审批");
		procurementApplicationService.save(procurementApplication);
		ApplicationApproval a=new ApplicationApproval();
		a.setCgsq(procurementApplication.getId());
		a.setDate(new Date());
		a.setAction("确认提交");
		a.setPerson(UserUtils.getUserName());
		applicationApprovalService.save(a);
		j.setMsg("确认成功");
		return j;
	}

	@RequestMapping(value = "updateStatus")
	@ResponseBody
	public String updateStatus( ProcurementApplication procurementApplication ,String yj,HttpServletResponse response,HttpServletRequest request) {
						String position=UserUtils.getposition();
						if(position.equals("办事处经理")){
							procurementApplication.setStatus("经理已审批");
						}
						if(position.contains("总监")){
							procurementApplication.setStatus("总监已审批");
						}NumberFormat nf = NumberFormat.getInstance();
						if(position.equals("总经理")){
							procurementApplication.setStatus("总经理已审批");
                           PaymentApplication p=new PaymentApplication();
                           p.setBm(procurementApplication.getBm());

                           p.setDate(procurementApplication.getDate());
							p.setSqr(procurementApplication.getSqr());
							p.setCgdh(procurementApplication.getCode());
							p.setType(procurementApplication.getType());
							p.setYy(procurementApplication.getCgsm());
							p.setJe(procurementApplication.getZjehs());
							p.setPro(procurementApplication.getPro());
							p.setStatus("已创建");
							p.setFkzt("未付款");
							SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
							String code=UserUtils.getUserAre()+sdf.format(new Date());
							PaymentApplication paymentApplication=new PaymentApplication();
							paymentApplication.setCode(code);
							List<PaymentApplication> list=paymentApplicationService.findList(paymentApplication);
							if(list==null||list.size()<1){
								p.setCode(code+"001"+"FKSQ");
							}else{
								if(list.size()/10==0){
									p.setCode(code+"00"+(list.size()+1)+"FKSQ");
								}else
								if(list.size()/100==0){
									p.setCode(code+"0"+(list.size()+1)+"FKSQ");
								}else{p.setCode(code+(list.size()+1)+"FKSQ");}

							}

							List<ApplicationDetil> l=procurementApplication.getApplicationDetilList();
							p.setXc(l.size()+"");
							service.save(p);
							for(ApplicationDetil a:l){
								PaymentDetil detil=new PaymentDetil();
								detil= (PaymentDetil) CopyUtil.Copy(detil,a,false);
								detil.setPyment(p);
								detil.setId(UUID.randomUUID().toString().replaceAll("-",""));
								paymentDetilMapper.insert(detil);
							}
						}
		ApplicationApproval a=new ApplicationApproval();
		a.setCgsq(procurementApplication.getId());
		a.setDate(new Date());
		a.setAction("审批通过");
		a.setPerson(UserUtils.getUserName());
		a.setReson(yj);
		applicationApprovalService.save(a);
		procurementApplicationService.save(procurementApplication);

		return "sesst";
	}



	@ResponseBody
	@RequestMapping(value = "bh")
	public AjaxJson bh(ProcurementApplication procurementApplication,String yj, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		procurementApplication.setStatus("审核未通过");
		ApplicationApproval a=new ApplicationApproval();
		a.setCgsq(procurementApplication.getId());
		a.setDate(new Date());
		a.setAction("驳回");
		a.setPerson(UserUtils.getUserName());
		a.setReson(yj);
		applicationApprovalService.save(a);
		procurementApplicationService.save(procurementApplication);
		j.setMsg("驳回成功");
		return j;
	}
	/**
	 * 删除采购申请
	 */
	@ResponseBody
	@RequiresPermissions("ap:procurementApplication:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(ProcurementApplication procurementApplication, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		procurementApplicationService.delete(procurementApplication);
		j.setMsg("删除采购申请成功");
		return j;
	}
	
	/**
	 * 批量删除采购申请
	 */
	@ResponseBody
	@RequiresPermissions("ap:procurementApplication:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			procurementApplicationService.delete(procurementApplicationService.get(id));
		}
		j.setMsg("删除采购申请成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("ap:procurementApplication:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(ProcurementApplication procurementApplication, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "采购申请"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ProcurementApplication> page = procurementApplicationService.findPage(new Page<ProcurementApplication>(request, response, -1), procurementApplication);
    		new ExportExcel("采购申请", ProcurementApplication.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出采购申请记录失败！失败信息："+e.getMessage());
		}
			return j;
    }
    
    @ResponseBody
    @RequestMapping(value = "detail")
	public ProcurementApplication detail(String id) {
		ProcurementApplication p=procurementApplicationService.get(id);
		ApplicationApproval a=new ApplicationApproval();
		a.setCgsq(id);
		List<ApplicationApproval> li=applicationApprovalService.findList(a);
		p.setApplicationApprovalsList(li);
		return p;
	}




	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("ap:procurementApplication:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ProcurementApplication> list = ei.getDataList(ProcurementApplication.class);
			for (ProcurementApplication procurementApplication : list){
				try{
					procurementApplicationService.save(procurementApplication);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条采购申请记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条采购申请记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入采购申请失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/procurementApplication/?repage";
    }
	
	/**
	 * 下载导入采购申请数据模板
	 */
	@RequiresPermissions("ap:procurementApplication:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "采购申请数据导入模板.xlsx";
    		List<ProcurementApplication> list = Lists.newArrayList(); 
    		new ExportExcel("采购申请数据", ProcurementApplication.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ap/procurementApplication/?repage";
    }
	

}